using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TangHotKey.Demo
{
    public partial class HotKeyEditForm : Form
    {
        public event EventHandler<HotKeyRegisteredEventArgs> HotKeyRegistered;
        
        public HotKeyEditForm()
        {
            InitializeComponent();
            InitializeForm();
        }

        private void InitializeForm()
        {
            // 初始化修饰键复选框
            checkBoxCtrl.Checked = false;
            checkBoxAlt.Checked = false;
            checkBoxShift.Checked = false;
            checkBoxWin.Checked = false;

            // 初始化主键下拉框
            comboBoxKey.Items.Clear();
            
            // 添加常用按键
            var commonKeys = new[]
            {
                Keys.A, Keys.B, Keys.C, Keys.D, Keys.E, Keys.F, Keys.G, Keys.H, Keys.I, Keys.J,
                Keys.K, Keys.L, Keys.M, Keys.N, Keys.O, Keys.P, Keys.Q, Keys.R, Keys.S, Keys.T,
                Keys.U, Keys.V, Keys.W, Keys.X, Keys.Y, Keys.Z,
                Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9,
                Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, Keys.F6, Keys.F7, Keys.F8, Keys.F9, Keys.F10, Keys.F11, Keys.F12,
                Keys.Space, Keys.Enter, Keys.Escape, Keys.Tab, Keys.Back, Keys.Delete,
                Keys.Home, Keys.End, Keys.PageUp, Keys.PageDown,
                Keys.Left, Keys.Right, Keys.Up, Keys.Down
            };

            foreach (var key in commonKeys)
            {
                comboBoxKey.Items.Add(key);
            }

            comboBoxKey.SelectedIndex = 0;
            textBoxDescription.Text = "";
            
            UpdatePreview();
        }

        private void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            UpdatePreview();
        }

        private void comboBoxKey_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdatePreview();
        }

        private void textBoxDescription_TextChanged(object sender, EventArgs e)
        {
            UpdatePreview();
        }

        private void UpdatePreview()
        {
            if (comboBoxKey.SelectedItem == null) return;

            var modifiers = HotKeyManager.ModifierKeys.None;
            if (checkBoxCtrl.Checked) modifiers |= HotKeyManager.ModifierKeys.Control;
            if (checkBoxAlt.Checked) modifiers |= HotKeyManager.ModifierKeys.Alt;
            if (checkBoxShift.Checked) modifiers |= HotKeyManager.ModifierKeys.Shift;
            if (checkBoxWin.Checked) modifiers |= HotKeyManager.ModifierKeys.Win;

            var key = (Keys)comboBoxKey.SelectedItem;
            var combination = new HotKeyCombination(modifiers, key, textBoxDescription.Text);
            
            labelPreview.Text = $"预览: {combination}";
            
            // 检查是否至少选择了一个修饰键
            buttonRegister.Enabled = modifiers != HotKeyManager.ModifierKeys.None;
        }

        private void buttonRegister_Click(object sender, EventArgs e)
        {
            if (comboBoxKey.SelectedItem == null) return;

            var modifiers = HotKeyManager.ModifierKeys.None;
            if (checkBoxCtrl.Checked) modifiers |= HotKeyManager.ModifierKeys.Control;
            if (checkBoxAlt.Checked) modifiers |= HotKeyManager.ModifierKeys.Alt;
            if (checkBoxShift.Checked) modifiers |= HotKeyManager.ModifierKeys.Shift;
            if (checkBoxWin.Checked) modifiers |= HotKeyManager.ModifierKeys.Win;

            var key = (Keys)comboBoxKey.SelectedItem;
            var description = string.IsNullOrWhiteSpace(textBoxDescription.Text) ? "自定义热键" : textBoxDescription.Text;

            // 触发事件，让主窗体处理注册
            var args = new HotKeyRegisteredEventArgs
            {
                Modifiers = modifiers,
                Key = key,
                Description = description
            };

            HotKeyRegistered?.Invoke(this, args);
            
            // 显示成功消息并关闭窗体
            MessageBox.Show($"热键 {new HotKeyCombination(modifiers, key, description)} 注册请求已发送！", 
                "注册热键", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonPreset1_Click(object sender, EventArgs e)
        {
            SetPreset(true, false, false, false, Keys.A, "复制操作");
        }

        private void buttonPreset2_Click(object sender, EventArgs e)
        {
            SetPreset(false, true, false, false, Keys.F1, "显示帮助");
        }

        private void buttonPreset3_Click(object sender, EventArgs e)
        {
            SetPreset(true, false, true, false, Keys.S, "保存文件");
        }

        private void SetPreset(bool ctrl, bool alt, bool shift, bool win, Keys key, string description)
        {
            checkBoxCtrl.Checked = ctrl;
            checkBoxAlt.Checked = alt;
            checkBoxShift.Checked = shift;
            checkBoxWin.Checked = win;
            
            comboBoxKey.SelectedItem = key;
            textBoxDescription.Text = description;
            
            UpdatePreview();
        }

        private void textBoxHotKeyInput_KeyDown(object sender, KeyEventArgs e)
        {
            // 获取按下的键和修饰键
            var modifiers = HotKeyManager.ModifierKeys.None;
            if (e.Control) modifiers |= HotKeyManager.ModifierKeys.Control;
            if (e.Alt) modifiers |= HotKeyManager.ModifierKeys.Alt;
            if (e.Shift) modifiers |= HotKeyManager.ModifierKeys.Shift;

            var key = e.KeyCode;

            // 过滤掉纯修饰键
            if (key == Keys.ControlKey || key == Keys.Menu || key == Keys.ShiftKey || 
                key == Keys.LControlKey || key == Keys.RControlKey ||
                key == Keys.LMenu || key == Keys.RMenu ||
                key == Keys.LShiftKey || key == Keys.RShiftKey)
            {
                return;
            }

            // 只有当有修饰键时才捕获热键组合
            if (modifiers != HotKeyManager.ModifierKeys.None)
            {
                // 阻止默认处理
                e.SuppressKeyPress = true;
                e.Handled = true;

                // 构建热键字符串
                var hotKeyText = BuildHotKeyString(modifiers, key);
                textBoxHotKeyInput.Text = hotKeyText;

                // 自动应用到界面
                ApplyHotKeyFromString(hotKeyText);
            }
            // 如果没有修饰键，允许正常的文本输入
        }

        private void buttonParseHotKey_Click(object sender, EventArgs e)
        {
            var input = textBoxHotKeyInput.Text.Trim();
            if (string.IsNullOrEmpty(input))
            {
                MessageBox.Show("请输入热键组合！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (ApplyHotKeyFromString(input))
            {
                MessageBox.Show("热键解析成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("热键格式不正确！\n\n支持的格式示例：\n- Ctrl+A\n- Alt+F1\n- Ctrl+Shift+S\n- Ctrl+Alt+Delete", 
                    "解析失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void buttonClearInput_Click(object sender, EventArgs e)
        {
            textBoxHotKeyInput.Clear();
            textBoxHotKeyInput.Focus();
        }

        private string BuildHotKeyString(HotKeyManager.ModifierKeys modifiers, Keys key)
        {
            var parts = new List<string>();

            if ((modifiers & HotKeyManager.ModifierKeys.Control) != 0) parts.Add("Ctrl");
            if ((modifiers & HotKeyManager.ModifierKeys.Alt) != 0) parts.Add("Alt");
            if ((modifiers & HotKeyManager.ModifierKeys.Shift) != 0) parts.Add("Shift");
            if ((modifiers & HotKeyManager.ModifierKeys.Win) != 0) parts.Add("Win");

            parts.Add(GetKeyDisplayName(key));

            return string.Join("+", parts);
        }

        private string GetKeyDisplayName(Keys key)
        {
            // 处理数字键
            if (key >= Keys.D0 && key <= Keys.D9)
            {
                return ((int)(key - Keys.D0)).ToString();
            }

            // 处理功能键
            if (key >= Keys.F1 && key <= Keys.F12)
            {
                return key.ToString();
            }

            // 处理特殊键
            switch (key)
            {
                case Keys.Space: return "Space";
                case Keys.Enter: return "Enter";
                case Keys.Escape: return "Esc";
                case Keys.Tab: return "Tab";
                case Keys.Back: return "Backspace";
                case Keys.Delete: return "Delete";
                case Keys.Home: return "Home";
                case Keys.End: return "End";
                case Keys.PageUp: return "PageUp";
                case Keys.PageDown: return "PageDown";
                case Keys.Left: return "Left";
                case Keys.Right: return "Right";
                case Keys.Up: return "Up";
                case Keys.Down: return "Down";
                default: return key.ToString();
            }
        }

        private bool ApplyHotKeyFromString(string hotKeyString)
        {
            try
            {
                var parts = hotKeyString.Split('+').Select(p => p.Trim()).ToArray();
                if (parts.Length < 2) return false;

                var modifiers = HotKeyManager.ModifierKeys.None;
                Keys key = Keys.None;

                // 解析修饰键和主键
                for (int i = 0; i < parts.Length; i++)
                {
                    var part = parts[i].ToLower();
                    
                    if (i == parts.Length - 1) // 最后一个是主键
                    {
                        key = ParseKey(parts[i]);
                        if (key == Keys.None) return false;
                    }
                    else // 修饰键
                    {
                        switch (part)
                        {
                            case "ctrl":
                            case "control":
                                modifiers |= HotKeyManager.ModifierKeys.Control;
                                break;
                            case "alt":
                                modifiers |= HotKeyManager.ModifierKeys.Alt;
                                break;
                            case "shift":
                                modifiers |= HotKeyManager.ModifierKeys.Shift;
                                break;
                            case "win":
                            case "windows":
                                modifiers |= HotKeyManager.ModifierKeys.Win;
                                break;
                            default:
                                return false;
                        }
                    }
                }

                // 应用到界面
                checkBoxCtrl.Checked = (modifiers & HotKeyManager.ModifierKeys.Control) != 0;
                checkBoxAlt.Checked = (modifiers & HotKeyManager.ModifierKeys.Alt) != 0;
                checkBoxShift.Checked = (modifiers & HotKeyManager.ModifierKeys.Shift) != 0;
                checkBoxWin.Checked = (modifiers & HotKeyManager.ModifierKeys.Win) != 0;

                // 设置主键
                if (comboBoxKey.Items.Contains(key))
                {
                    comboBoxKey.SelectedItem = key;
                }
                else
                {
                    // 如果下拉框中没有这个键，添加它
                    comboBoxKey.Items.Add(key);
                    comboBoxKey.SelectedItem = key;
                }

                UpdatePreview();
                return true;
            }
            catch
            {
                return false;
            }
        }

        private Keys ParseKey(string keyString)
        {
            var key = keyString.Trim();
            
            // 处理数字
            if (key.Length == 1 && char.IsDigit(key[0]))
            {
                return Keys.D0 + (key[0] - '0');
            }

            // 处理字母
            if (key.Length == 1 && char.IsLetter(key[0]))
            {
                return (Keys)Enum.Parse(typeof(Keys), key.ToUpper());
            }

            // 处理特殊键名
            switch (key.ToLower())
            {
                case "space": return Keys.Space;
                case "enter": return Keys.Enter;
                case "esc": case "escape": return Keys.Escape;
                case "tab": return Keys.Tab;
                case "backspace": return Keys.Back;
                case "delete": case "del": return Keys.Delete;
                case "home": return Keys.Home;
                case "end": return Keys.End;
                case "pageup": return Keys.PageUp;
                case "pagedown": return Keys.PageDown;
                case "left": return Keys.Left;
                case "right": return Keys.Right;
                case "up": return Keys.Up;
                case "down": return Keys.Down;
            }

            // 尝试直接解析
            if (Enum.TryParse<Keys>(key, true, out Keys result))
            {
                return result;
            }

            return Keys.None;
        }
    }

    public class HotKeyRegisteredEventArgs : EventArgs
    {
        public HotKeyManager.ModifierKeys Modifiers { get; set; }
        public Keys Key { get; set; }
        public string Description { get; set; }
    }
}